﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Ornament.MemberShip;
using Ornament.MemberShip.Permissions;
using Ornament.MVCWebFrame.Models;
using Ornament.Web;
using Ornament.Web.Mvc;
using Ornament.Web.Mvc.JQuery.JQGrid;

namespace Ornament.MVCWebFrame.Areas.MemberShips.Controllers
{
    /// <summary>
    /// </summary>   
    public class RoleController : Controller
    {
        // GET: /Role/

        /// <summary>
        /// </summary>
        /// <param name="pageIndex">
        /// The page index.
        /// </param>
        /// <returns>
        /// </returns>        
        public ActionResult Index()
        {
            ViewData["permissions"] = from p in OrnamentContext.Current.MemberShipFactory.Permissions select p;

            return View();
        }

        /// <summary>
        /// </summary>
        /// <param name="roleName">
        /// The role name.
        /// </param>
        /// <returns>
        /// </returns>
        public ActionResult GetRole(string roleName)
        {
            Role role = OrnamentContext.Current.MemberShipFactory.Roles.Where(r => r.Name == roleName)
                .SingleOrDefault();
            var result = new
                             {
                                 role.Name,
                                 role.Comment,
                                 Permissions = (from p in role.Permissions select p.Id)
                             };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// </summary>
        /// <param name="subMitData">
        /// The sub mit data.
        /// </param>
        /// <returns>
        /// </returns>
        /// 
        public ActionResult GetRoles(
            [ModelBinder(typeof(JQGridSubmitDataBinder))] 
            JQGridSubmitData submitData)
        {
            IRoleDao roleDao = OrnamentContext.Current.MemberShipFactory.CreateRoleDao();
            IOrderedQueryable<Role> resultEntities = from role in
                                                         OrnamentContext.Current.MemberShipFactory.Roles
                                                         .Skip(submitData.PageIndex * submitData.PageSize)
                                                         .Take(submitData.PageSize)
                                                     orderby role.Name
                                                     select role;

            JQGridResult result = submitData.Create();
            result.total = roleDao.CountAll();

            foreach (Role u in resultEntities)
            {
                result.rows.Add(new JQItem
                                    {
                                        id = u.Name,
                                        cell = new ArrayList
                                                   {
                                                       u.Name,
                                                       u.Comment
                                                   }
                                    });
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// </summary>
        /// <param name="role">
        /// The role.
        /// </param>
        /// <returns>
        /// </returns>
        [JsonContainerFilter]
        public ActionResult Save(JsonContainer role)
        {
            Role roleEntity = OrnamentContext.Current.MemberShipFactory.CreateRoleDao().Get(role.ToString("Name")) ??
                              new Role(role.ToString("Name"));

            roleEntity.Comment = role.ToString("Comment");
            roleEntity.Permissions.Clear();

            IPermissionDao permissionDao = OrnamentContext.Current.MemberShipFactory.CreatePermissionDao();

            foreach (string id in role.ToArray<string>("permissions"))
            {
                roleEntity.Permissions.Add(permissionDao.Get(new Guid(id)));
            }
            return Json(new ReturnResult("保存成功", true), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult Delete(string name)
        {
            string[] roleNames = name.Split(',');

            IRoleDao dao = OrnamentContext.Current.MemberShipFactory.CreateRoleDao();
            string[] canBeDeletedRoles;

            IList<Role> cannotDeleteRole = dao.GetInUseRoles(roleNames, out canBeDeletedRoles);


            foreach (Role deleteRole in dao.GetRoles(canBeDeletedRoles))
            {
                if (deleteRole.Name == "admin")
                    continue;
                dao.Delete(deleteRole);
            }

            var sb = new StringBuilder();

            if (canBeDeletedRoles.Length != 0)
            {
                sb.Append("以下Roles已经被删除" + String.Join(",", canBeDeletedRoles));
            }

            if (cannotDeleteRole.Count != 0)
            {
                IEnumerable<string> roles = from role in cannotDeleteRole select role.Name;
                sb.Append(String.Join(",", roles.ToArray()));
            }
            if (cannotDeleteRole.Count == 0 && canBeDeletedRoles.Length == 0)
            {
                sb.Append("没有可以删除的Role");
            }
            return Json(sb.ToString(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult ListRolesByName(string name, int pageSize, int pageIndex)
        {

            IRoleDao roleDao = OrnamentContext.Current.MemberShipFactory.CreateRoleDao();
            IOrderedQueryable<Role> resultEntities = from role in
                                                         OrnamentContext.Current.MemberShipFactory.Roles
                                                         .Skip(pageIndex * pageSize)
                                                         .Take(pageSize)
                                                     where role.Name.IndexOf(name) != -1
                                                     orderby role.Name
                                                     select role;
            return Json(resultEntities);
        }
    }
}